<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQL生成工具</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="js/jquery-3.6.0.min.js"></script>
    <style>
        :root {
            --primary: #4361ee;
            --primary-light: #e0e7ff;
            --secondary: #3f37c9;
            --dark: #1e293b;
            --light: #f8fafc;
            --gray: #94a3b8;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        
        [data-theme="dark"] {
            --primary: #4361ee;
            --primary-light: #2d3748;
            --secondary: #3f37c9;
            --dark: #f8fafc;
            --light: #1e293b;
            --gray: #64748b;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--light);
            color: var(--dark);
            height: 100vh;
            display: grid;
            grid-template-rows: auto 1fr auto;
        }
        
        /* 顶部导航栏 */
        .navbar {
            background-color: var(--light);
            padding: 0.75rem 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .logo-icon {
            width: 32px;
            height: 32px;
            background-color: var(--primary);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .logo-text {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--dark);
        }
        
        .user-controls {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--secondary);
        }

        .btn-primary:disabled {
            background-color: #6c757d;
            border-color: #6c757d;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--gray);
            color: var(--dark);
        }
        
        .btn-outline:hover {
            background-color: var(--light);
        }
        
        .btn-outline:disabled {
            background-color: #f1f5f9;
            border-color: #cbd5e1;
            color: #94a3b8;
            cursor: not-allowed;
            opacity: 0.7;
        }
        
        /* 主内容区 */
        .main-content {
            display: grid;
            grid-template-columns: 300px 1fr;
            height: 100%;
            overflow: hidden;
        }
        
        /* 左侧边栏 */
        .sidebar {
            background-color: var(--light);
            border-right: 1px solid var(--gray);
            padding: 1.5rem;
            overflow-y: auto;
            scrollbar-width: none;
        }
        
        .sidebar-section {
            margin-bottom: 2rem;
        }
        
        .sidebar-title {
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--gray);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .connection-item {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            border-radius: 6px;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
        }
        
        .connection-item:hover {
            background-color: var(--primary-light);
        }
        
        .connection-item.active {
            background-color: var(--primary-light);
            border-left: 3px solid var(--primary);
        }
        
        .connection-icon {
            width: 24px;
            height: 24px;
            margin-right: 0.75rem;
            color: var(--primary);
        }
        
        .connection-name {
            font-weight: 500;
            flex-grow: 1;
        }
        
        .connection-type {
            font-size: 0.6rem;
            color: var(--gray);
            background-color: var(--light);
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
        }
        
        .connection-actions {
            display: flex;
            gap: 0.5rem;
            margin-right: 0.75rem;
            opacity: 0;
            transition: opacity 0.2s;
            position: absolute;
            right: 0;
        }
        
        .connection-item:hover .connection-actions {
            opacity: 1;
        }
        
        .connection-more-btn {
            background: none;
            border: none;
            color: var(--dark);
            opacity: 0;
            transition: opacity 0.2s;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .connection-item:hover .connection-more-btn {
            opacity: 1;
        }
        
        .context-menu-item:hover {
            background-color: var(--primary-light);
        }
        
        .connection-btn {
            background: none;
            border: 1px solid var(--gray);
            color: var(--gray);
            cursor: pointer;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        
        .connection-btn.connect-btn {
            border-color: var(--success);
            color: var(--success);
        }
        
        .connection-btn.disconnect-btn {
            border-color: var(--danger);
            color: var(--danger);
        }
        
        .connection-btn:hover {
            background-color: var(--light);
        }
        
        .connection-btn.connect-btn:hover {
            background-color: var(--success);
            color: white;
        }
        
        .connection-btn.disconnect-btn:hover {
            background-color: var(--danger);
            color: white;
        }
        
        /* 隐藏连接状态显示 */
        .connection-status {
            display: none;
        }
        
        .table-list {
            margin-top: 1rem;
            max-height: 350px;
            overflow-y: auto;
            scrollbar-width: none;
        }
        
        .table-controls {
            display: flex;
            flex-direction: row;
            gap: 0.5rem;
            margin-bottom: 1rem;
            align-items: center;
        }
        
        .table-filter {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--gray);
            border-radius: 6px;
            font-family: inherit;
            background-color: var(--light);
            color: var(--dark);
        }
        
        .table-buttons {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .table-buttons .btn {
            width: auto;
            margin-bottom: 0;
        }
        
        .table-controls .btn {
            width: auto;
            margin-bottom: 0;
        }
        
        .select-all-container {
            display: flex;
            align-items: center;
            margin-top: 0.2rem;
        }
        
        .select-all-checkbox {
            margin-right: 0.1rem;
        }
        
        .select-all-label {
            width: 3rem;
            font-size: 0.8rem;
            color: var(--gray);
            cursor: pointer;
        }
        
        .table-item {
            display: flex;
            align-items: center;
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            margin-bottom: 0.25rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .table-item:hover {
            background-color: var(--primary-light);
        }
        
        .table-item.selected {
            background-color: var(--primary-light);
        }
        
        .table-checkbox {
            margin-right: 0.75rem;
        }
        
        .table-name {
            font-size: 0.875rem;
        }
        
        /* 主工作区 */
        .workspace {
            padding: 1.5rem;
            display: grid;
            grid-template-rows: auto 1fr auto;
            gap: 1.5rem;
            overflow-y: auto;
        }
        
        .selected-tables {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .table-chip {
            background-color: var(--primary-light);
            color: var(--primary);
            padding: 0.25rem 0.75rem;
            border-radius: 999px;
            font-size: 0.75rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .table-chip-remove {
            cursor: pointer;
        }
        
        .input-area {
            background-color: var(--light);
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
        }
        
        .input-title {
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .input-hint {
            font-size: 0.75rem;
            color: var(--gray);
        }
        
        .natural-language-input {
            width: 100%;
            min-height: 120px;
            padding: 1rem;
            border: 1px solid var(--gray);
            border-radius: 6px;
            font-family: inherit;
            resize: none;
            transition: all 0.2s;
            background-color: var(--light);
            color: var(--dark);
        }
        
        .natural-language-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }
        
        .output-area {
            background-color: var(--light);
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
        }
        
        .sql-output {
            width: 100%;
            min-height: 120px;
            padding: 1rem;
            background-color: var(--light);
            border: 1px solid var(--gray);
            border-radius: 6px;
            font-family: monospace;
            white-space: pre-wrap;
            overflow-x: auto;
            color: var(--dark);
        }
        
        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }
        
        /* 底部状态栏 */
        .status-bar {
            background-color: var(--light);
            padding: 0.75rem 1.5rem;
            border-top: 1px solid var(--gray);
            font-size: 0.75rem;
            color: var(--gray);
            display: flex;
            justify-content: space-between;
        }
        
        /* 添加连接模态框 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }
        
        .modal-overlay.active {
            opacity: 1;
            pointer-events: all;
        }
        
        .modal {
            background-color: var(--light);
            border-radius: 8px;
            width: 700px;
            height: 650px;
            max-width: 90%;
            max-height: 90%;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            transform: translateY(20px);
            transition: transform 0.3s;
            display: flex;
            flex-direction: column;
        }
        
        .modal-overlay.active .modal {
            transform: translateY(0);
        }
        
        .modal-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid var(--gray);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 1.125rem;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--gray);
        }
        
        .modal-body {
            padding: 1.0rem;
            color: var(--dark);
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }
        
        .form-group {
            margin-bottom: 1.25rem;
        }
        
        .form-group-full {
            grid-column: span 2;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            font-size: 0.875rem;
        }
        
        .form-control {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid var(--gray);
            border-radius: 6px;
            font-family: inherit;
            transition: all 0.2s;
            background-color: var(--light);
            color: var(--dark);
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }
        
        .form-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%2394a3b8' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 16px 12px;
            background-color: var(--light);
            color: var(--dark);
        }
        
        .modal-footer {
            padding: 1.25rem 1.5rem;
            border-top: 1px solid var(--gray);
            display: flex;
            justify-content: flex-end;
            gap: 0.75rem;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .sidebar {
                display: none;
            }
            
            .sidebar.active {
                display: block;
                position: fixed;
                top: 0;
                left: 0;
                width: 80%;
                height: 100%;
                z-index: 20;
            }
            
            .mobile-menu-btn {
                display: block;
            }
        }

        .table-cell-full {
            max-width: 250px;
            display: inline-block;
            word-wrap: break-word;
            white-space: normal;
            overflow: hidden;
        }
        
        /* 字段搜索结果表格滚动条 */
        .table-responsive {
            overflow-x: hidden;
            overflow-y: auto;
            max-height: 480px;
            position: relative;
        }
        
        .table-responsive::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        .table-responsive::-webkit-scrollbar-track {
            background: var(--light);
            border-radius: 4px;
        }
        
        .table-responsive::-webkit-scrollbar-thumb {
            background: var(--gray);
            border-radius: 4px;
        }
        
        .table-responsive::-webkit-scrollbar-thumb:hover {
            background: var(--dark);
        }
        
        /* 固定表头 */
        .table-responsive thead th {
            position: sticky;
            top: 0;
            background-color: var(--primary-light);
            z-index: 1;
        }
        
        /* 设置模态框样式 */
        .settings-container {
            display: flex;
            height: 80%;
        }
        
        .settings-sidebar {
            width: 200px;
            border-right: 1px solid var(--gray);
            padding: 1rem;
        }
        
        .settings-menu-item {
            padding: 0.75rem 1rem;
            border-radius: 6px;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .settings-menu-item:hover {
            background-color: var(--primary-light);
        }
        
        .settings-menu-item.active {
            background-color: var(--primary-light);
            border-left: 3px solid var(--primary);
        }
        
        .settings-content {
            flex: 1;
            padding: 1rem;
        }
        
        .settings-panel {
            display: none;
        }
        
        .settings-panel.active {
            display: block;
        }
        
        /* 查询结果表格样式 */
        .query-results-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.875rem;
        }
        
        .query-results-table th {
            background-color: var(--primary-light);
            padding: 8px 12px;
            text-align: left;
            border-bottom: 1px solid var(--gray);
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 1;
        }
        
        .query-results-table td {
            padding: 8px 12px;
            border-bottom: 1px solid var(--gray);
            word-wrap: break-word;
            max-width: 200px;
        }
        
        .query-results-table tr:hover {
            background-color: var(--primary-light);
        }
        
        /* 分页样式 */
        .pagination {
            margin-top: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.875rem;
        }
        
        .pagination-info {
            color: var(--gray);
        }
        
        .pagination-controls {
            display: flex;
            gap: 5px;
        }
        
        .page-size-control {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .page-size-control select {
            width: 80px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="logo">
            <div class="logo-icon">GS</div>
            <div class="logo-text">SQL生成工具</div>
        </div>
        <div class="user-controls">
            <button class="btn btn-outline" id="theme-toggle-btn">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M8 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM8 13A5 5 0 1 0 8 3a5 5 0 0 0 0 10z"/>
                </svg>
                切换主题
            </button>
            <button class="btn btn-outline" id="settings-btn">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                </svg>
                设置
            </button>
            <button class="btn btn-primary" id="new-connection-btn">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                </svg>
                添加连接
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 左侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-section">
                <div class="sidebar-title">数据库连接</div>
                <div class="connection-list">
                </div>
            </div>
            
            <div class="sidebar-section">
                <div class="sidebar-title">数据库表
                    <button class="btn btn-outline" id="search-columns-btn" title="搜索字段">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
                        </svg>
                    </button>
                </div>
                <div class="table-controls">
                    <input type="text" class="form-control table-filter" placeholder="搜索表名...">
                    <div class="select-all-container">
                        <input type="checkbox" id="select-all-checkbox" class="select-all-checkbox">
                        <label for="select-all-checkbox" class="select-all-label">全选</label>
                    </div>
                </div>
                <div class="table-list">
                </div>
            </div>
        </div>
        
        <!-- 设置模态框 -->
        <div class="modal-overlay" id="settings-modal">
            <div class="modal">
                <div class="modal-header">
                    <div class="modal-title">设置</div>
                    <button class="modal-close" id="close-settings-modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="settings-container">
                        <div class="settings-sidebar">
                            <div class="settings-menu-item active" data-target="model-settings">模型设置</div>
                        </div>
                        <div class="settings-content">
                            <div class="settings-panel active" id="model-settings">
                                <div class="form-group">
                                    <label class="form-label">API URL</label>
                                    <input type="text" class="form-control" id="api-url" placeholder="请输入 API URL">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Provider</label>
                                    <input type="text" class="form-control" id="provider" placeholder="请输入 Provider">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Model</label>
                                    <input type="text" class="form-control" id="model" placeholder="请输入 Model">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">API Key</label>
                                    <input type="password" class="form-control" id="api-key" placeholder="请输入 API Key">
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-primary" id="save-settings-btn">保存</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 新建查询模态框 -->
        <div class="modal-overlay" id="query-modal">
            <div class="modal" style="width: 90%; height: 80%;">
                <div class="modal-header">
                    <div class="modal-title">新建查询</div>
                    <button class="modal-close" id="close-query-modal-btn">&times;</button>
                </div>
                <div class="modal-body" style="flex-grow: 1; display: flex; flex-direction: column;">
                    <div class="form-group" style="margin-bottom: 15px;">
                        <label class="form-label">SQL语句</label>
                        <textarea class="form-control" id="sql-input" placeholder="请输入SQL语句..." style="height: 120px; resize: vertical;"></textarea>
                    </div>
                    <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                        <button class="btn btn-primary" id="execute-sql-btn">执行查询</button>
                        <button class="btn btn-outline" id="clear-sql-btn">清空</button>
                    </div>
                    <div class="form-group" style="flex-grow: 1; display: flex; flex-direction: column;">
                        <label class="form-label">查询结果</label>
                        <div class="table-responsive" style="height: 200px; overflow-y: auto; border: 1px solid var(--gray); border-radius: 6px;">
                            <table class="table" style="width: 100%; border-collapse: collapse;" id="query-results-table">
                                <thead>
                                    <tr style="background-color: var(--primary-light);">
                                        <!-- 表头将动态生成 -->
                                    </tr>
                                </thead>
                                <tbody id="query-results-body">
                                    <!-- 查询结果将在这里显示 -->
                                </tbody>
                            </table>
                        </div>
                        <div class="pagination" style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center;">
                            <div class="pagination-info" id="pagination-info">
                                第 <span id="current-page">1</span> 页，共 <span id="total-pages">1</span> 页，共 <span id="total-records">0</span> 条记录
                            </div>
                            <div class="pagination-controls" style="display: flex; gap: 5px;">
                                <button class="btn btn-outline" id="first-page-btn" disabled>首页</button>
                                <button class="btn btn-outline" id="prev-page-btn" disabled>上一页</button>
                                <button class="btn btn-outline" id="next-page-btn" disabled>下一页</button>
                                <button class="btn btn-outline" id="last-page-btn" disabled>末页</button>
                            </div>
                            <div class="page-size-control" style="display: flex; align-items: center; gap: 5px;">
                                <span>每页显示:</span>
                                <select class="form-control" id="page-size-select" style="width: 80px;">
                                    <option value="10">10</option>
                                    <option value="20" selected>20</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                </select>
                                <span>条</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 主工作区 -->
        <div class="workspace">
            <div class="selected-tables">
<!--                <div class="table-chip">-->
<!--                    users-->
<!--                    <span class="table-chip-remove">-->
<!--                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">-->
<!--                            <line x1="18" y1="6" x2="6" y2="18"></line>-->
<!--                            <line x1="6" y1="6" x2="18" y2="18"></line>-->
<!--                        </svg>-->
<!--                    </span>-->
<!--                </div>-->
<!--                <div class="table-chip">-->
<!--                    orders-->
<!--                    <span class="table-chip-remove">-->
<!--                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">-->
<!--                            <line x1="18" y1="6" x2="6" y2="18"></line>-->
<!--                            <line x1="6" y1="6" x2="18" y2="18"></line>-->
<!--                        </svg>-->
<!--                    </span>-->
<!--                </div>-->
            </div>
            
            <div class="input-area">
                <div class="input-title">
                    输入自然语言查询
                    <span class="input-hint">例如："查询最近30天下单金额超过1000元的用户"</span>
                </div>
                <textarea class="natural-language-input" placeholder="请输入您的查询需求..."></textarea>
            </div>
            
            <div class="output-area">
                <div class="input-title">生成的SQL语句</div>
                <div class="sql-output"></div>
            </div>
            
            <div class="action-buttons">
                <button class="btn btn-outline" id="new-query-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                        <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                    </svg>
                    新建查询
                </button>
                <button class="btn btn-outline">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                        <path d="M5.5 7a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1h-5zM5 9.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.5-.5z"/>
                        <path d="M9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.5L9.5 0zm0 1v2A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5z"/>
                    </svg>
                    复制SQL
                </button>
                <button class="btn btn-primary">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                        <path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/>
                    </svg>
                    生成SQL
                </button>
            </div>
        </div>
    </div>
    
    <!-- 底部状态栏 -->
    <div class="status-bar">
        <div>已选择: 未选择</div>
        <div>已选择 0 个表</div>
    </div>
    
    <!-- 添加连接模态框 -->
    <div class="modal-overlay" id="connection-modal">
        <div class="modal">
            <div class="modal-header">
                <div class="modal-title">添加数据库连接</div>
                <button class="modal-close" id="close-modal-btn">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">连接名称</label>
                        <input type="text" class="form-control" id="connection-name" placeholder="例如: 生产数据库">
                    </div>
                    <div class="form-group">
                        <label class="form-label">数据库类型</label>
                        <select class="form-control form-select" id="connection-type">
                            <option value="">选择数据库类型</option>
                            <option value="mysql">MySQL</option>
                            <option value="postgresql">PostgreSQL</option>
                            <option value="kingbase">Kingbase</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">主机地址</label>
                        <input type="text" class="form-control" id="connection-host" placeholder="例如: localhost 或 192.168.1.100">
                    </div>
                    <div class="form-group">
                        <label class="form-label">端口</label>
                        <input type="text" class="form-control" id="connection-port" placeholder="例如: 3306">
                    </div>
                    <div class="form-group form-group-full">
                        <label class="form-label">catalog</label>
                        <input type="text" class="form-control" id="connection-catalog" placeholder="mysql无需填写">
                    </div>
                    <div class="form-group form-group-full">
                        <label class="form-label">schema</label>
                        <input type="text" class="form-control" id="connection-database" placeholder="mysql填写数据库名">
                    </div>
                    <div class="form-group">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" id="connection-username" placeholder="数据库用户名">
                    </div>
                    <div class="form-group">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" id="connection-password" placeholder="数据库密码">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline" id="cancel-modal-btn">取消</button>
                <button class="btn btn-outline" id="test-connection-btn">测试连接</button>
                <button class="btn btn-primary" id="save-connection-btn">保存连接</button>
            </div>
        </div>
    </div>
    
    <!-- 字段搜索模态框 -->
    <div class="modal-overlay" id="column-search-modal">
        <div class="modal" style="width: 80%;">
            <div class="modal-header">
                <div class="modal-title">字段搜索</div>
                <button class="modal-close" id="close-column-search-modal-btn">&times;</button>
            </div>
            <div class="modal-body" style="flex-grow: 1; display: flex; flex-direction: column;">
                <div class="form-group" style="display: flex; gap: 10px; align-items: center;">
                    <input type="text" class="form-control" id="column-search-input" placeholder="请输入关键字" style="flex-grow: 1;width: 80%;">
                    <button class="btn btn-primary" id="column-search-btn" style="writing-mode: horizontal-tb;">查询</button>
                </div>
                <div class="table-responsive" style="margin-top: 15px; flex-grow: 1; overflow-y: auto;">
                    <table class="table" style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background-color: var(--primary-light);">
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">表名</th>
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">表注释</th>
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">列名</th>
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">类型</th>
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">可空</th>
                                <th style="padding: 10px; text-align: center; border-bottom: 1px solid var(--gray);">列注释</th>
                            </tr>
                        </thead>
                        <tbody id="column-search-results" style="background-color: var(--light); text-align: center;">
                            <!-- 搜索结果将在这里显示 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Theme toggle functionality
        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
        }
        
        // Initialize theme on page load
        function initTheme() {
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme) {
                document.documentElement.setAttribute('data-theme', savedTheme);
            }
        }
        
        // Add event listener to theme toggle button
        document.addEventListener('DOMContentLoaded', function() {
            initTheme();
            const themeToggleBtn = document.getElementById('theme-toggle-btn');
            if (themeToggleBtn) {
                themeToggleBtn.addEventListener('click', toggleTheme);
            }
        });
        
        // Mock data for database connections
        const mockConnections = [];
        
        // Mock data for database tables
        const mockTables = [
        ];
        
        // Function to fetch connections from API
        function fetchConnections() {
            return $.get('/getConnections')
                .then(response => {
                    if (response.code === 0) {
                        return response.data;
                    } else {
                        throw new Error(response.msg || 'Failed to fetch connections');
                    }
                })
                .catch(error => {
                    console.error('Error fetching connections:', error);
                    // Fallback to mock data if API call fails
                    return mockConnections;
                });
        }
        
        // Function to save connection status to session storage
        function saveConnectionStatus(connectionId, isConnected) {
            // Get current connection statuses from session storage
            let connectionStatuses = sessionStorage.getItem('connectionStatuses');
            connectionStatuses = connectionStatuses ? JSON.parse(connectionStatuses) : {};
            
            // Update the status for this connection
            connectionStatuses[connectionId] = isConnected;
            
            // Save back to session storage
            sessionStorage.setItem('connectionStatuses', JSON.stringify(connectionStatuses));
        }
        
        // Function to load connection status from session storage
        function loadConnectionStatus(connectionId) {
            // Get current connection statuses from session storage
            let connectionStatuses = sessionStorage.getItem('connectionStatuses');
            connectionStatuses = connectionStatuses ? JSON.parse(connectionStatuses) : {};
            
            // Return the status for this connection, or null if not found
            return connectionStatuses.hasOwnProperty(connectionId) ? connectionStatuses[connectionId] === true : null;
        }
        
        // Function to fetch tables for a connection from API
        function fetchTables(connectionId) {
            return $.get(`/getTables?connectionId=${connectionId}`)
                .then(response => {
                    if (response.code === 0) {
                        return response.data;
                    } else {
                        throw new Error(response.msg || 'Failed to fetch tables');
                    }
                })
                .catch(error => {
                    console.error('Error fetching tables:', error);
                    // Fallback to mock data if API call fails
                    const tables = mockTables.filter(table => table.connectionId === connectionId);
                    return tables;
                });
        }
        
        // Render connections in the sidebar
        function renderConnections(connections) {
            const connectionList = $('.connection-list');
            connectionList.empty();
            
            connections.forEach((connection, index) => {
                // Check if connection status is saved in session storage
                const isSavedConnected = loadConnectionStatus(connection.id);
                // Use saved status if available, otherwise use the status from the API
                const isConnected = isSavedConnected !== null ? isSavedConnected : connection.status === '已连接';
                const buttonText = isConnected ? '断开' : '连接';
                const buttonClass = isConnected ? 'disconnect-btn' : 'connect-btn';
                
                const connectionItem = `
                    <div class="connection-item ${index === 0 ? 'active' : ''}" data-id="${connection.id}">
                        <div class="connection-type">${connection.type}</div>
                        <div class="connection-name">${connection.name}</div>
                        <span class="connection-status ${isConnected ? 'connected' : 'disconnected'}" style="display: none;">${isConnected ? '已连接' : '断开'}</span>
                        <div class="connection-actions">
                            <button class="connection-btn ${buttonClass}" title="${buttonText}">
                                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
                                    <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
                                    <path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
                                </svg>
                            </button>
                            <button class="connection-more-btn" title="更多操作">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                                    <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                `;
                connectionList.append(connectionItem);
            });
            
            // Add click event listeners to connection items
            $('.connection-item').on('click', function(e) {
                // Only proceed if clicking on the connection item itself, not on buttons
                if (!$(e.target).hasClass('connection-btn') && !$(e.target).hasClass('connection-more-btn') && $(e.target).closest('.connection-btn').length === 0 && $(e.target).closest('.connection-more-btn').length === 0) {
                    $('.connection-item').removeClass('active');
                    $(this).addClass('active');
                    
                    // Clear selected tables when switching connections
                    $('.selected-tables').empty();
                    $('.table-item').removeClass('selected');
                    $('.table-checkbox').prop('checked', false);
                    
                    // Only fetch tables if connection is active
                    const connectionStatus = $(this).find('.connection-status').hasClass('connected');
                    if (connectionStatus) {
                        const connectionId = $(this).data('id');
                        fetchTables(connectionId).then(tables => {
                            renderTables(tables);
                        });
                    } else {
                        // Clear tables if connection is not active
                        $('.table-list').empty();
                    }
                    
                    // Update status bar
                    updateStatusBar();
                }
            });

            // Add click event listeners to connection buttons
            $('.connection-list .connection-btn').on('click', function(e) {
                e.stopPropagation(); // Prevent triggering the connection item click event
                
                const connectionItem = $(this).closest('.connection-item');
                const connectionId = connectionItem.data('id');
                const connectionName = connectionItem.find('.connection-name').text();
                const isConnected = connectionItem.find('.connection-status').hasClass('connected');
                if (isConnected) {
                    // Disconnect
                    // Update connection status directly without API call
                    connectionItem.find('.connection-status').removeClass('connected').addClass('disconnected').text('断开');
                    
                    // Update button to show connect icon
                    const connectBtn = $(this);
                    connectBtn.removeClass('disconnect-btn').addClass('connect-btn');
                    connectBtn.attr('title', '连接');
                    connectBtn.html(`
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
                            <path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
                        </svg>
                    `);
                    
                    // If this connection is active, clear its tables
                    if (connectionItem.hasClass('active')) {
                        $('.table-list').empty();
                    }
                    
                    // Save connection status to session storage
                    saveConnectionStatus(connectionId, false);
                    
                    // alert(`连接 "${connectionName}" 已断开`);
                } else {
                    let btnThis = this;
                    // Connect
                    // Call connect API
                    $.ajax({
                        url: `/connection?connectionId=${connectionId}`,
                        method: 'GET',
                        success: function(response) {
                            if (response.code === 0) {
                                // Update connection status
                                connectionItem.find('.connection-status').removeClass('disconnected').addClass('connected').text('已连接');

                                // Update button to show disconnect icon
                                const connectBtn = $(btnThis);
                                connectBtn.removeClass('connect-btn').addClass('disconnect-btn');
                                connectBtn.attr('title', '断开');
                                connectBtn.html(`
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
                                        <path d="M11.534 7h-3.932a.25.25 0 0 1-.192-.41l1.966-2.36a.25.25 0 0 1 .384 0l1.966 2.36a.25.25 0 0 1-.192.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
                                        <path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
                                    </svg>
                                `);
                                
                                // If this connection is active, fetch its tables
                                if (connectionItem.hasClass('active')) {
                                    fetchTables(connectionId).then(tables => {
                                        renderTables(tables);
                                    });
                                }
                                
                                // Save connection status to session storage
                                saveConnectionStatus(connectionId, true);
                                
                                // alert(`连接 "${connectionName}" 成功`);
                            } else {
                                alert('连接失败: ' + response.msg);
                            }
                        },
                        error: function() {
                            alert('连接时发生错误');
                        }
                    });
                }
            });
            
            // Add click event listeners to more connection buttons
            $('.connection-list').on('click', '.connection-more-btn', function(e) {
                e.stopPropagation(); // Prevent triggering the connection item click event
                
                const connectionItem = $(this).closest('.connection-item');
                const connectionId = connectionItem.data('id');
                const connectionName = connectionItem.find('.connection-name').text();
                
                // Create context menu
                const contextMenu = $(`
                    <div class="connection-context-menu" style="position: absolute; top: ${e.pageY}px; left: ${e.pageX}px; background: var(--light); border: 1px solid var(--gray); border-radius: 6px; padding: 5px; z-index: 1000; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <div class="context-menu-item" data-action="edit" style="padding: 8px 12px; cursor: pointer; border-radius: 4px;">编辑</div>
                        <div class="context-menu-item" data-action="delete" style="padding: 8px 12px; cursor: pointer; border-radius: 4px; color: var(--danger);">删除</div>
                    </div>
                `);
                
                // Add context menu to body
                $('body').append(contextMenu);
                
                // Handle context menu item clicks
                contextMenu.on('click', '.context-menu-item', function() {
                    const action = $(this).data('action');
                    
                    if (action === 'delete') {
                        // Show confirmation dialog
                        if (confirm(`确定要删除连接 "${connectionName}" 吗？`)) {
                            // Call delete connection API
                            $.ajax({
                                url: `/deleteConnection/${connectionId}`,
                                method: 'DELETE',
                                success: function(response) {
                                    if (response.code === 0) {
                                        // Remove the connection item from the list
                                        connectionItem.remove();
                                        
                                        fetchConnections().then(connections => {
                                            renderConnections(connections);
                                        });
                                        
                                        // Update status bar
                                        updateStatusBar();
                                    } else {
                                        alert('删除失败: ' + response.msg);
                                    }
                                },
                                error: function() {
                                    alert('删除连接时发生错误');
                                }
                            });
                        }
                    } else if (action === 'edit') {
                        // Implement edit functionality
                        const connectionItem = $(e.target).closest('.connection-item');
                        const connectionId = connectionItem.data('id');
                        
                        // Fetch connection details from server
                        $.get(`/getConnection/${connectionId}`)
                            .done(function(response) {
                                if (response.code === 0) {
                                    const connection = response.data;
                                    
                                    // Fill the modal with existing connection data
                                    $('#connection-name').val(connection.name);
                                    $('#connection-type').val(connection.type);
                                    $('#connection-host').val(connection.host);
                                    $('#connection-port').val(connection.port);
                                    $('#connection-database').val(connection.database);
                                    $('#connection-catalog').val(connection.catalog);
                                    $('#connection-username').val(connection.username);
                                    $('#connection-password').val(connection.password);
                                    
                                    // Store the connection ID in a data attribute for later use
                                    $('#connection-modal').data('connection-id', connectionId);
                                    
                                    // Change the modal title and submit button text
                                    $('#connection-modal .modal-title').text('编辑数据库连接');
                                    $('#save-connection-btn').text('更新连接');
                                    
                                    // Show the modal
                                    $('#connection-modal').addClass('active');
                                } else {
                                    alert('获取连接详情失败: ' + response.msg);
                                }
                            })
                            .fail(function() {
                                alert('获取连接详情时发生错误');
                            });
                    }
                    
                    // Remove context menu
                    contextMenu.remove();
                });
                
                // Remove context menu when clicking elsewhere
                $(document).one('click', function() {
                    contextMenu.remove();
                });
            });
        }
        
        // Render tables in the sidebar
        function renderTables(tables) {
            const tableList = $('.table-list');
            tableList.empty();
            
            tables.forEach(table => {
                const tableItem = `
                    <div class="table-item" data-id="${table.id}">
                        <input type="checkbox" class="table-checkbox">
                        <div class="table-name" title="${table.comment}">${table.name}</div>
                    </div>
                `;
                tableList.append(tableItem);
            });
            
            // Add click event listeners to table items
            $('.table-item').on('click', function(e) {
                if (!$(e.target).is('.table-checkbox')) {
                    const checkbox = $(this).find('.table-checkbox');
                    checkbox.prop('checked', !checkbox.prop('checked'));
                }
                
                if ($(this).find('.table-checkbox').prop('checked')) {
                    $(this).addClass('selected');
                } else {
                    $(this).removeClass('selected');
                }
                
                updateSelectedTables();
            });
            
            // Select all tables
            $('#select-all-checkbox').on('change', function() {
                const isChecked = $(this).prop('checked');
                $('.table-item').each(function() {
                    if ($(this).is(':visible')) { // Only select visible items
                        $(this).find('.table-checkbox').prop('checked', isChecked);
                        if (isChecked) {
                            $(this).addClass('selected');
                        } else {
                            $(this).removeClass('selected');
                        }
                    }
                });
                updateSelectedTables();
            });
            
            // Filter tables
            $('.table-filter').on('input', function() {
                const filterValue = $(this).val().toLowerCase();
                $('.table-item').each(function() {
                    const tableName = $(this).find('.table-name').text().toLowerCase();
                    if (tableName.includes(filterValue)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
                // Update select all checkbox state after filtering
                updateSelectedTables();
            });
        }
        
        // Update selected tables display
        function updateSelectedTables() {
            const selectedTables = $('.table-item.selected .table-name').map(function() {
                return $(this).text();
            }).get();
            
            const selectedTablesContainer = $('.selected-tables');
            selectedTablesContainer.empty();
            
            selectedTables.forEach(tableName => {
                const tableChip = `
                    <div class="table-chip" data-table-name="${tableName}">
                        ${tableName}
                        <span class="table-chip-remove">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </span>
                    </div>
                `;
                selectedTablesContainer.append(tableChip);
            });
            
            // Add click event for removing table chips
            $('.table-chip-remove').on('click', function() {
                const chip = $(this).closest('.table-chip');
                const tableName = chip.data('table-name');
                
                // Uncheck the corresponding table item
                $(`.table-item.selected .table-name`).filter(function() {
                    return $(this).text() === tableName;
                }).closest('.table-item').removeClass('selected').find('.table-checkbox').prop('checked', false);
                
                // Remove the chip
                chip.remove();
                
                // Update status bar
                updateStatusBar();
            });
            
            // Update select all checkbox state
            const allVisibleTables = $('.table-item:visible');
            const allVisibleSelectedTables = $('.table-item.selected:visible');
            
            if (allVisibleTables.length === 0) {
                $('#select-all-checkbox').prop('checked', false);
                $('#select-all-checkbox').prop('indeterminate', false);
            } else if (allVisibleSelectedTables.length === allVisibleTables.length) {
                $('#select-all-checkbox').prop('checked', true);
                $('#select-all-checkbox').prop('indeterminate', false);
            } else if (allVisibleSelectedTables.length === 0) {
                $('#select-all-checkbox').prop('checked', false);
                $('#select-all-checkbox').prop('indeterminate', false);
            } else {
                $('#select-all-checkbox').prop('checked', false);
                $('#select-all-checkbox').prop('indeterminate', true);
            }
            
            // Update status bar
            updateStatusBar();
        }
        
        // Update status bar
        function updateStatusBar() {
            const selectedTableCount = $('.table-chip').length;
            const activeConnection = $('.connection-item.active .connection-name').text();
            const connectionType = $('.connection-item.active .connection-type').text();
            $('.status-bar div:first').text(`已选择: ${activeConnection} (${connectionType})`);
            $('.status-bar div:last').text(`已选择 ${selectedTableCount} 个表`);
        }
        
        // Initialize the application
        $(document).ready(function() {
            // Fetch and render connections
            fetchConnections().then(connections => {
                renderConnections(connections);
                
                // Fetch and render tables for the first connection
                // if (connections.length > 0) {
                //     fetchTables(connections[0].id).then(tables => {
                //         renderTables(tables);
                //     });
                // }
            });
            
            // Modal functionality
            $('#new-connection-btn').on('click', function() {
                // Reset all form fields
                $('#connection-name').val('');
                $('#connection-type').val('');
                $('#connection-host').val('');
                $('#connection-port').val('');
                $('#connection-catalog').val('');
                $('#connection-database').val('');
                $('#connection-username').val('');
                $('#connection-password').val('');
                
                // Reset modal title and submit button text
                $('#connection-modal .modal-title').text('添加数据库连接');
                $('#save-connection-btn').text('保存连接');
                
                // Remove connection ID data attribute
                $('#connection-modal').removeData('connection-id');
                
                $('#connection-modal').addClass('active');
            });
            
            $('#close-modal-btn, #cancel-modal-btn').on('click', function() {
                $('#connection-modal').removeClass('active');
                
                // Reset all form fields
                $('#connection-name').val('');
                $('#connection-type').val('');
                $('#connection-host').val('');
                $('#connection-port').val('');
                $('#connection-catalog').val('');
                $('#connection-database').val('');
                $('#connection-username').val('');
                $('#connection-password').val('');
                
                // Reset modal title and submit button text
                $('#connection-modal .modal-title').text('添加数据库连接');
                $('#save-connection-btn').text('保存连接');
                
                // Remove connection ID data attribute
                $('#connection-modal').removeData('connection-id');
            });
            
            // Column search functionality
            $('#search-columns-btn').on('click', function() {
                $('#column-search-modal').addClass('active');
                $('#column-search-modal .modal-title').html('字段搜索');
                // Clear previous search results
                $('#column-search-input').val('');
                $('#column-search-results').empty();
            });
            
            $('#close-column-search-modal-btn').on('click', function() {
                $('#column-search-modal').removeClass('active');
            });
            
            $('#column-search-btn').on('click', function() {
                const keyword = $('#column-search-input').val().trim();
                if (keyword === '') {
                    alert('请输入搜索关键字');
                    return;
                }
                
                // Get selected connection
                const selectedConnection = $('.connection-item.active').data('id');
                if (!selectedConnection) {
                    alert('请选择一个数据库连接');
                    return;
                }
                
                // Show loading state
                const $searchBtn = $(this);
                const originalText = $searchBtn.html();
                $searchBtn.prop('disabled', true).html('搜索中...');
                
                // Call search columns API
                $.ajax({
                    url: `/searchColumns?connectionId=${selectedConnection}&keyword=${encodeURIComponent(keyword)}`,
                    method: 'GET',
                    success: function(response) {
                        if (response.code === 0) {
                            // Render search results
                            const results = response.data;
                            const $tbody = $('#column-search-results');
                            $tbody.empty();
                            
                            if (results.length === 0) {
                                $tbody.append('<tr><td colspan="6">未找到匹配的字段</td></tr>');
                            } else {
                                results.forEach(item => {
                                    const row = `
                                        <tr>
                                            <td><span class="table-cell-full" title="${item.tableName}">${item.tableName}</span></td>
                                            <td><span class="table-cell-full" title="${item.tableComment || ''}">${item.tableComment || ''}</span></td>
                                            <td><span class="table-cell-full" title="${item.columnName}">${item.columnName}</span></td>
                                            <td><span class="table-cell-full" title="${item.columnType}">${item.columnType}</span></td>
                                            <td>${item.nullable ? '是' : '否'}</td>
                                            <td><span class="table-cell-full" title="${item.columnComment || ''}">${item.columnComment || ''}</span></td>
                                        </tr>
                                    `;
                                    $tbody.append(row);
                                });
                            }
                        } else {
                            alert('搜索失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        alert('搜索时发生错误');
                    },
                    complete: function() {
                        // Restore button state
                        $searchBtn.html(originalText).prop('disabled', false);
                    }
                });
            });
            
            // Allow search when pressing Enter in the search input
            $('#column-search-input').on('keypress', function(e) {
                if (e.which === 13) { // Enter key
                    $('#column-search-btn').click();
                }
            });
            
            // Copy SQL functionality
            $('.action-buttons .btn-outline').eq(1).on('click', function() {
                const sqlOutput = $('.sql-output').text().trim();
                
                if (!sqlOutput) {
                    alert('请先生成SQL语句');
                    return;
                }
                
                // Create temporary textarea to copy text
                const $temp = $('<textarea>');
                $('body').append($temp);
                $temp.val(sqlOutput).select();
                document.execCommand('copy');
                $temp.remove();
                
                // Show feedback to user
                const originalText = $(this).html();
                $(this).html('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/></svg> 已复制');
                
                // Reset button text after 2 seconds
                setTimeout(() => {
                    $(this).html(originalText);
                }, 2000);
            });
            
            // Generate SQL button functionality
            const $generateSqlBtn = $('.action-buttons .btn-primary');
            const $naturalLanguageInput = $('.natural-language-input');
            const $sqlOutput = $('.sql-output');
            
            // Function to update generate SQL button state
            function updateGenerateSqlButtonState() {
                if ($naturalLanguageInput.val().trim() === '') {
                    $generateSqlBtn.prop('disabled', true);
                } else {
                    $generateSqlBtn.prop('disabled', false);
                }
            }
            
            // Initialize button state
            updateGenerateSqlButtonState();
            
            // Add input event listener to natural language input
            $naturalLanguageInput.on('input', function() {
                updateGenerateSqlButtonState();
            });
            
            // Add click event listener to generate SQL button
            $generateSqlBtn.on('click', function() {
                const naturalLanguageQuery = $naturalLanguageInput.val().trim();
                
                // Get selected connection and tables
                const selectedConnection = $('.connection-item.active').data('id');
                const selectedTables = $('.table-item.selected .table-name').map(function() {
                    return $(this).text();
                }).get();
                
                // Prepare data for API call
                const requestData = {
                    query: naturalLanguageQuery,
                    connectionId: selectedConnection,
                    tableNames: selectedTables
                };
                
                // Show loading state
                const originalText = $generateSqlBtn.html();
                $generateSqlBtn.html('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/><path d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/></svg> 生成中...');
                $generateSqlBtn.prop('disabled', true);
                $sqlOutput.text('');
                
                // Call generate SQL API
                $.ajax({
                    url: '/generateSql',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function(response) {
                        if (response.code === 0) {
                            $sqlOutput.text(response.data);
                        } else {
                            $sqlOutput.text('生成SQL失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        $sqlOutput.text('生成SQL时发生错误');
                    },
                    complete: function() {
                        // Restore button state
                        $generateSqlBtn.html(originalText);
                        updateGenerateSqlButtonState();
                    }
                });
            });
            
            // Save connection functionality
            $('#save-connection-btn').on('click', function() {
                // Check if we're editing an existing connection
                const connectionId = $('#connection-modal').data('connection-id');
                
                // Get form values
                const connectionName = $('#connection-name').val().trim();
                const connectionType = $('#connection-type').val();
                const connectionHost = $('#connection-host').val().trim();
                const connectionPort = $('#connection-port').val().trim();
                const connectionCatalog = $('#connection-catalog').val().trim();
                const connectionDatabase = $('#connection-database').val().trim();
                const connectionUsername = $('#connection-username').val().trim();
                const connectionPassword = $('#connection-password').val().trim();
                
                // Validate form fields
                if (!connectionName) {
                    alert('请输入连接名称');
                    return;
                }
                
                if (!connectionType) {
                    alert('请选择数据库类型');
                    return;
                }
                
                if (!connectionHost) {
                    alert('请输入主机地址');
                    return;
                }
                
                if (!connectionPort) {
                    alert('请输入端口');
                    return;
                }
                
                // Only require catalog if database type is not MySQL
                if (connectionType !== 'mysql' && !connectionCatalog) {
                    alert('请输入catalog');
                    return;
                }
                
                if (!connectionDatabase) {
                    alert('请输入schema');
                    return;
                }
                
                if (!connectionUsername) {
                    alert('请输入用户名');
                    return;
                }

                const connectionData = {
                    name: connectionName,
                    type: connectionType,
                    host: connectionHost,
                    port: connectionPort,
                    catalog: connectionCatalog,
                    database: connectionDatabase,
                    username: connectionUsername,
                    password: connectionPassword
                };
                
                let url = '/saveConnection';
                let method = 'POST';
                
                // If we're editing an existing connection, update the URL and method
                if (connectionId) {
                    // Add the ID to the connection data
                    connectionData.id = connectionId;
                }
                
                // Send data to server
                $.ajax({
                    url: url,
                    method: method,
                    contentType: 'application/json',
                    data: JSON.stringify(connectionData),
                    success: function(response) {
                        if (response.code === 0) {
                            alert(connectionId ? '连接更新成功' : '连接保存成功');
                            $('#connection-modal').removeClass('active');
                            
                            // Reset modal title and submit button text
                            $('#connection-modal .modal-title').text('添加数据库连接');
                            $('#save-connection-btn').text('保存连接');
                            
                            // Remove connection ID data attribute
                            $('#connection-modal').removeData('connection-id');
                            
                            // Refresh connections list
                            fetchConnections().then(connections => {
                                renderConnections(connections);
                            });
                        } else {
                            alert('保存失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        alert('保存连接时发生错误');
                    }
                });
            });
            
            // Test connection functionality
            $('#test-connection-btn').on('click', function() {
                // Get form values
                const connectionName = $('#connection-name').val().trim();
                const connectionType = $('#connection-type').val();
                const connectionHost = $('#connection-host').val().trim();
                const connectionPort = $('#connection-port').val().trim();
                const connectionCatalog = $('#connection-catalog').val().trim();
                const connectionDatabase = $('#connection-database').val().trim();
                const connectionUsername = $('#connection-username').val().trim();
                const connectionPassword = $('#connection-password').val().trim();
                
                // Validate form fields
                if (!connectionName) {
                    alert('请输入连接名称');
                    return;
                }
                
                if (!connectionType) {
                    alert('请选择数据库类型');
                    return;
                }
                
                if (!connectionHost) {
                    alert('请输入主机地址');
                    return;
                }
                
                if (!connectionPort) {
                    alert('请输入端口');
                    return;
                }
                
                // Only require catalog if database type is not MySQL
                if (connectionType !== 'mysql' && !connectionCatalog) {
                    alert('请输入catalog');
                    return;
                }
                
                if (!connectionDatabase) {
                    alert('请输入schema');
                    return;
                }
                
                if (!connectionUsername) {
                    alert('请输入用户名');
                    return;
                }

                const connectionData = {
                    name: connectionName,
                    type: connectionType,
                    host: connectionHost,
                    port: connectionPort,
                    catalog: connectionCatalog,
                    database: connectionDatabase,
                    username: connectionUsername,
                    password: connectionPassword
                };
                
                // Send data to server for testing connection
                $.ajax({
                    url: '/testConnection',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(connectionData),
                    success: function(response) {
                        if (response.code === 0) {
                            alert('连接测试成功');
                        } else {
                            alert('连接测试失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        alert('测试连接时发生错误');
                    }
                });
            });

            // 设置模态框显示/隐藏功能
            document.getElementById('settings-btn').addEventListener('click', function() {
                // 调用 /getModelSetting 接口初始化数据
                $.ajax({
                    url: '/getModelSetting',
                    method: 'GET',
                    success: function(response) {
                        if (response.code === 0 && response.data) {
                            const data = response.data;
                            document.getElementById('api-url').value = data.apiUrl || '';
                            document.getElementById('provider').value = data.provider || '';
                            document.getElementById('model').value = data.model || '';
                            document.getElementById('api-key').value = data.apiKey || '';
                        }
                    },
                    error: function() {
                        console.error('获取模型设置失败');
                    }
                });

                document.getElementById('settings-modal').getElementsByClassName('modal-title')[0].textContent = '设置';
                document.getElementById('settings-modal').classList.add('active');
            });

            // 点击模态框关闭按钮关闭模态框
            document.getElementById('close-settings-modal').addEventListener('click', function(e) {
                e.stopPropagation(); // 阻止事件冒泡
                document.getElementById('settings-modal').classList.remove('active');
            });

            // 选项卡切换功能
            document.querySelectorAll('.settings-menu-item').forEach(item => {
                item.addEventListener('click', function() {
                    // 移除所有选项卡的激活状态
                    document.querySelectorAll('.settings-menu-item').forEach(i => {
                        i.classList.remove('active');
                    });

                    // 添加当前选项卡的激活状态
                    this.classList.add('active');

                    // 隐藏所有设置面板
                    document.querySelectorAll('.settings-panel').forEach(panel => {
                        panel.classList.remove('active');
                    });

                    // 显示当前选中的设置面板
                    const target = this.getAttribute('data-target');
                    document.getElementById(target).classList.add('active');
                });
            });

            // 保存设置功能
            document.getElementById('save-settings-btn').addEventListener('click', function() {
                const apiUrl = document.getElementById('api-url').value;
                const provider = document.getElementById('provider').value;
                const model = document.getElementById('model').value;
                const apiKey = document.getElementById('api-key').value;

                // 调用 /saveModelSetting 接口保存设置
                $.ajax({
                    url: '/saveModelSetting',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        apiUrl: apiUrl,
                        provider: provider,
                        model: model,
                        apiKey: apiKey
                    }),
                    success: function(response) {
                        if (response.code === 0) {
                            alert('设置保存成功');
                        } else {
                            alert('保存失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        alert('保存设置时发生错误');
                    }
                });

                // 保存成功后关闭模态框
                document.getElementById('settings-modal').classList.remove('active');
            });

            // 新建查询功能
            let currentQueryData = {
                results: [],
                currentPage: 1,
                pageSize: 20,
                totalRecords: 0
            };

            // 新建查询按钮点击事件
            document.getElementById('new-query-btn').addEventListener('click', function() {
                // 检查是否有已连接的数据库
                const activeConnection = document.querySelector('.connection-item.active');
                if (!activeConnection) {
                    alert('请先选择一个已连接的数据库');
                    return;
                }
                
                const connectionStatus = activeConnection.querySelector('.connection-status');
                if (!connectionStatus || !connectionStatus.classList.contains('connected')) {
                    alert('请先连接数据库');
                    return;
                }

                // 显示查询模态框
                document.getElementById('query-modal').classList.add('active');
                
                // 清空SQL输入框
                document.getElementById('sql-input').value = '';
                
                // 重置查询结果
                clearQueryResults();
            });

            // 关闭查询模态框
            document.getElementById('close-query-modal-btn').addEventListener('click', function(e) {
                e.stopPropagation();
                document.getElementById('query-modal').classList.remove('active');
            });

            // 清空SQL按钮
            document.getElementById('clear-sql-btn').addEventListener('click', function() {
                document.getElementById('sql-input').value = '';
            });

            // 执行查询按钮
            document.getElementById('execute-sql-btn').addEventListener('click', function() {
                executeQuery();
            });

            // 分页控制按钮
            document.getElementById('first-page-btn').addEventListener('click', function() {
                goToPage(1);
            });

            document.getElementById('prev-page-btn').addEventListener('click', function() {
                goToPage(currentQueryData.currentPage - 1);
            });

            document.getElementById('next-page-btn').addEventListener('click', function() {
                goToPage(currentQueryData.currentPage + 1);
            });

            document.getElementById('last-page-btn').addEventListener('click', function() {
                goToPage(Math.ceil(currentQueryData.totalRecords / currentQueryData.pageSize));
            });

            // 每页显示数量变化
            document.getElementById('page-size-select').addEventListener('change', function() {
                currentQueryData.pageSize = parseInt(this.value);
                currentQueryData.currentPage = 1;
                if (currentQueryData.results.length > 0) {
                    executeQuery(); // 重新执行查询以获取新的分页数据
                }
            });

            // 执行查询函数
            function executeQuery() {
                const sql = document.getElementById('sql-input').value.trim();
                if (!sql) {
                    alert('请输入SQL语句');
                    return;
                }

                // 获取当前连接的ID
                const activeConnection = document.querySelector('.connection-item.active');
                const connectionId = activeConnection.getAttribute('data-id');

                // 显示加载状态
                const executeBtn = document.getElementById('execute-sql-btn');
                const originalText = executeBtn.textContent;
                executeBtn.textContent = '执行中...';
                executeBtn.disabled = true;

                // 发送查询请求，包含分页参数
                $.ajax({
                    url: '/executeQuery',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        connectionId: connectionId,
                        sql: sql,
                        currentPage: currentQueryData.currentPage,
                        pageSize: currentQueryData.pageSize
                    }),
                    success: function(response) {
                        if (response.code === 0) {
                            currentQueryData.results = response.data.records || [];
                            currentQueryData.totalRecords = response.data.totalRecords || 0;
                            
                            renderQueryResults();
                        } else {
                            alert('查询失败: ' + response.msg);
                        }
                    },
                    error: function() {
                        alert('执行查询时发生错误');
                    },
                    complete: function() {
                        executeBtn.textContent = originalText;
                        executeBtn.disabled = false;
                    }
                });
            }

            // 渲染查询结果
            function renderQueryResults() {
                const tableBody = document.getElementById('query-results-body');
                const tableHead = document.querySelector('#query-results-table thead tr');
                
                // 清空表格
                tableHead.innerHTML = '';
                tableBody.innerHTML = '';

                if (currentQueryData.results.length === 0) {
                    const row = document.createElement('tr');
                    const cell = document.createElement('td');
                    cell.colSpan = 1;
                    cell.textContent = '无查询结果';
                    cell.style.textAlign = 'center';
                    cell.style.padding = '20px';
                    row.appendChild(cell);
                    tableBody.appendChild(row);
                    updatePaginationInfo();
                    return;
                }

                // 获取列名
                const firstRow = currentQueryData.results[0];
                const columns = Object.keys(firstRow);

                // 创建表头 - 添加序号列
                const indexTh = document.createElement('th');
                indexTh.textContent = '序号';
                indexTh.style.padding = '10px';
                indexTh.style.textAlign = 'center';
                indexTh.style.borderBottom = '1px solid var(--gray)';
                tableHead.appendChild(indexTh);

                columns.forEach(col => {
                    const th = document.createElement('th');
                    th.textContent = col;
                    th.style.padding = '10px';
                    th.style.textAlign = 'center';
                    th.style.borderBottom = '1px solid var(--gray)';
                    tableHead.appendChild(th);
                });

                // 直接显示后端返回的当前页数据
                currentQueryData.results.forEach((rowData, rowIndex) => {
                    const row = document.createElement('tr');
                    
                    // 添加序号列
                    const indexCell = document.createElement('td');
                    indexCell.textContent = (currentQueryData.currentPage - 1) * currentQueryData.pageSize + rowIndex + 1;
                    indexCell.style.padding = '10px';
                    indexCell.style.textAlign = 'center';
                    indexCell.style.borderBottom = '1px solid var(--gray)';
                    indexCell.style.fontWeight = 'bold';
                    row.appendChild(indexCell);
                    
                    columns.forEach(col => {
                        const cell = document.createElement('td');
                        cell.textContent = rowData[col] !== null && rowData[col] !== undefined ? rowData[col].toString() : '';
                        cell.style.padding = '10px';
                        cell.style.textAlign = 'center';
                        cell.style.borderBottom = '1px solid var(--gray)';
                        cell.style.wordWrap = 'break-word';
                        cell.style.maxWidth = '200px';
                        row.appendChild(cell);
                    });
                    
                    tableBody.appendChild(row);
                });

                updatePaginationInfo();
            }

            // 更新分页信息
            function updatePaginationInfo() {
                const totalPages = Math.ceil(currentQueryData.totalRecords / currentQueryData.pageSize);
                
                document.getElementById('current-page').textContent = currentQueryData.currentPage;
                document.getElementById('total-pages').textContent = totalPages;
                document.getElementById('total-records').textContent = currentQueryData.totalRecords;

                // 更新分页按钮状态
                const hasData = currentQueryData.totalRecords > 0;
                document.getElementById('first-page-btn').disabled = !hasData || currentQueryData.currentPage <= 1;
                document.getElementById('prev-page-btn').disabled = !hasData || currentQueryData.currentPage <= 1;
                document.getElementById('next-page-btn').disabled = !hasData || currentQueryData.currentPage >= totalPages;
                document.getElementById('last-page-btn').disabled = !hasData || currentQueryData.currentPage >= totalPages;
            }

            // 跳转到指定页面
            function goToPage(page) {
                const totalPages = Math.ceil(currentQueryData.totalRecords / currentQueryData.pageSize);
                
                if (page < 1) page = 1;
                if (page > totalPages) page = totalPages;
                
                currentQueryData.currentPage = page;
                if (currentQueryData.results.length > 0) {
                    executeQuery(); // 重新执行查询以获取指定页的数据
                }
            }

            // 清空查询结果
            function clearQueryResults() {
                currentQueryData = {
                    results: [],
                    currentPage: 1,
                    pageSize: 20,
                    totalRecords: 0
                };
                
                document.getElementById('query-results-body').innerHTML = '';
                document.querySelector('#query-results-table thead tr').innerHTML = '';
                updatePaginationInfo();
            }

            // 支持按Enter键执行查询
            document.getElementById('sql-input').addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && e.ctrlKey) {
                    e.preventDefault();
                    executeQuery();
                }
            });
        });
    </script>
</body>
</html>